package com.adv.ems.config;

import com.adv.ems.model.dto.APIResponse;
import com.adv.ems.model.dto.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<Object> exception(Exception e) {
        log.error("程序错误", e);
        return ResponseEntity.status(500).body(APIResponse.systemError("服务器内部错误", e.getMessage()));
    }

    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public ResponseEntity<Object> handleBusinessException(Exception e) {
        BusinessException e1 = (BusinessException) e;
        log.error("业务异常{}", e1.getMsg());
        return ResponseEntity.status(200).body(APIResponse.businessError(e1.getCode(), e1.getMsg()));
    }

    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    @ResponseBody
    public ResponseEntity<Object> handleHttpMessageNotReadableException(Exception e) {
        log.error("参数错误", e);
        return ResponseEntity.status(200).body(APIResponse.systemError("参数错误", e.getMessage()));
    }
}
